package com.kongchengji.zhanguafou.controller;
import com.kongchengji.zhanguafou.constant.WxInfo;
import com.kongchengji.zhanguafou.dao.QuartzDAO;
import com.kongchengji.zhanguafou.domain.ICPDO;
import com.kongchengji.zhanguafou.domain.QuartzDO;
import com.kongchengji.zhanguafou.domain.Result;
import com.kongchengji.zhanguafou.service.ICPService;
import com.kongchengji.zhanguafou.utils.InfoByCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletResponse;


@Controller
@RequestMapping("/icp")
public class ICPController {
    @Autowired
    private ICPService icpService;
    @Autowired
    private QuartzDAO quartzDAO;


    /**
     * 将请求转发到icp配置页
     * @param code
     * @return
     */
    @RequestMapping("/forwardConfig")
    public String forwardIcpConfig(@RequestParam String code,Model model){
        //微信网页授权,通过code换取accesstoken,最终获取openId
        WxInfo.openId = InfoByCodeUtil.getOpenId(code);
        model.addAttribute("isSave",true);
        //转发到icp备案配置界面
        return "icp_config";
    }

    /**
     *保存配置信息
     * @param icpdo icp对象
     * @param bindingResult 校验结果信息对象
     * @return 返回结果
     */
    @RequestMapping("/saveConfig")
    @ResponseBody
    public Result saveConfig(@Validated ICPDO icpdo, BindingResult bindingResult){
        //设置openId
        icpdo.setOpenId(WxInfo.openId);
        if(bindingResult.hasErrors()){
            for(ObjectError error:bindingResult.getAllErrors()){
                return Result.error(error.getDefaultMessage());
            }
        }
       return icpService.saveConfig(icpdo);
    }


    /**
     * 打开编辑页面
     * @param groupName 监控的域名
     * @return
     */
    @RequestMapping("/openIcpEditPage")
    public String openEditPage(@RequestParam String groupName,Model model, HttpServletResponse response) {
        String jobName = groupName + WxInfo.openId;
        Example example = new Example(QuartzDO.class);
        example.createCriteria().andEqualTo("jobName",jobName);
        QuartzDO quartzDO = quartzDAO.selectOneByExample(example);
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        model.addAttribute("quartzDO",quartzDO);
        model.addAttribute("isQuartzEdit",true);
        return "icp_config";
    }


}
